/*
 * Copyright (C) 2009 Rafael Fernandes
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.phonebooksharing.android.activities.dashboard;

import java.util.ArrayList;
import java.util.HashMap;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.format.DateUtils;
import android.view.View;
import android.view.ViewStub;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import com.phonebooksharing.android.R;
import com.phonebooksharing.android.activities.contacts.ContactBrowserActivity;
import com.phonebooksharing.android.async.SendTextMessageTask;
import com.phonebooksharing.android.async.SendVoiceMessageTask;
import com.phonebooksharing.android.util.GeneralUtils;
import com.phonebooksharing.android.util.Global;
import com.phonebooksharing.dto.dashboard.DashboardReaderItem;
import com.phonebooksharing.dto.friend.ContactItem;
import com.phonebooksharing.dto.msg.TextMessageItem;

@SuppressWarnings("unchecked")
public abstract class AbstractReaderActivity extends Activity {

    public static final String  FRIEND_ICON     = "i", 
                                FRIEND_NAME     = "n",
                                FRIEND_STATUS   = "s",
                                FRIEND_LOCATION = "l",
                                FRIEND_ID       = "fi",
                                SENT_WHEN       = "sw",
                                DASHBOARD_ID    = "d",
                                DASHBOARD_READER_ITEM = "dr",
                                CONTACT_ITEM    = "cc";
    
    public static final String  READ_AUDIO        = "a",
                                READ_TEXT         = "t",
                                READ_PHOTO        = "p";
    
    protected Animation anim;
    protected long dashboardID, friendID;
    protected DashboardReaderItem<ContactItem> dashItem;
    protected ContactItem focusContact;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.event_reader);
        
        anim = AnimationUtils.loadAnimation(this, R.anim.slide_left_in);

        final Intent intent = getIntent();

        dashboardID = intent.getLongExtra(DASHBOARD_ID, 0);
        friendID    = intent.getLongExtra(FRIEND_ID, 0);
        dashItem    = (DashboardReaderItem<ContactItem>)intent.getSerializableExtra(DASHBOARD_READER_ITEM);
        
        if(dashItem != null) {
            focusContact = dashItem.getItem();
        } else {
            focusContact= (ContactItem)intent.getSerializableExtra(CONTACT_ITEM);
        }
        
        ((ImageView)findViewById(android.R.id.icon)).setImageBitmap((Bitmap)intent.getParcelableExtra(FRIEND_ICON));
        ((TextView)findViewById(android.R.id.text1)).setText(intent.getStringExtra(FRIEND_NAME));
        ((TextView)findViewById(R.id.text3)).setText(intent.getStringExtra(FRIEND_STATUS));
        long l;
        if((l = intent.getLongExtra(SENT_WHEN, 0)) > 0) {
            ((TextView)findViewById(android.R.id.text2)).setText("(" + DateUtils.getRelativeTimeSpanString(l,
                    System.currentTimeMillis(), DateUtils.MINUTE_IN_MILLIS, DateUtils.FORMAT_ABBREV_RELATIVE) + ")");
        }
        ((TextView)findViewById(R.id.text4)).setText(intent.getStringExtra(FRIEND_LOCATION));
        
        final ListView lv = (ListView)findViewById(android.R.id.list);
        lv.setAdapter(new SimpleAdapter(this, getActions(),
                R.layout.list_item_3lines, 
                new String[]{"i","t","d"}, new int[]{android.R.id.icon, android.R.id.text1, R.id.text3}));
        
        setupActionClick(lv);
    }
    
    protected void setupActionClick(final ListView lv) {
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int position, long id) {
                switch (position) {
                    case 0: { //record new
//                        lv.setVisibility(View.GONE);
                        
                        Intent i = new Intent(MediaStore.Audio.Media.RECORD_SOUND_ACTION);
                        startActivityForResult(i, ACTIVITY_RECORD_SOUND);
                        break;
                    }
                    case 1: { //new text
                        lv.setVisibility(View.GONE);
                        preparePostText();
                        break;
                    }
                    case 2: { //contact browser
//                        ContactBrowserActivity cb = new ContactBrowserActivity();
                        Intent i = new Intent(AbstractReaderActivity.this, ContactBrowserActivity.class);
                        i.putExtra(ContactBrowserActivity.FRIEND_ITEM, focusContact);
                        startActivity(i);
                        break;
                    }
                    case 3: { //send mail
                        GeneralUtils.sendEmail(AbstractReaderActivity.this, friendID, "", "");
                        break;
                    }
                    case 4: { //send SMS
                        GeneralUtils.sendSMS(AbstractReaderActivity.this, friendID, "");
                        break;
                    }
                    default:
                        break;
                }
            }
        });
    }
    
    protected ArrayList<HashMap<String, String>> getActions() {
        ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();

        HashMap<String, String> opt = new HashMap<String, String>();
        opt.put("i", String.valueOf(R.drawable.dash_videos));
        opt.put("t", "Post a Voice Message");
        opt.put("d", "You can post a voice response");
        list.add(opt);
        
        opt = new HashMap<String, String>();
        opt.put("i", String.valueOf(R.drawable.dash_messages));
        opt.put("t", "Post a Text Message");
        opt.put("d", "You can post a text response");
        list.add(opt);
        
        opt = new HashMap<String, String>();
        opt.put("i", String.valueOf(R.drawable.friends));
        opt.put("t", "Contact Browser");
        opt.put("d", "Browse on his friends account");
        list.add(opt);
        
        opt = new HashMap<String, String>();
        opt.put("i", String.valueOf(R.drawable.email));
        opt.put("t", "Send an Email");
        opt.put("d", "You can respond by mail");
        list.add(opt);
        
        opt = new HashMap<String, String>();
        opt.put("i", String.valueOf(R.drawable.send_sms));
        opt.put("t", "Send a SMS");
        opt.put("d", "You can respond by SMS");
        list.add(opt);
        
        opt = new HashMap<String, String>();
        opt.put("i", String.valueOf(R.drawable.loading_icon));
        opt.put("t", "Make a phone call");
        opt.put("d", "Just give them a call");
        list.add(opt);
        
        //TODO: add chat here with status
//        opt = new HashMap<String, String>();
//        opt.put("i", String.valueOf(R.drawable.loading_icon));
//        opt.put("t", "Send a SMS");
//        opt.put("d", "You can respond by SMS");
//        list.add(opt);
        
        return list;
    }
    
    protected OnClickListener backListener = new OnClickListener() {
        @Override
        public void onClick(View v) {
            View vv = (View)v.getParent().getParent().getParent();
            vv.setVisibility(View.GONE);
            
            View l = findViewById(android.R.id.list);
            l.setVisibility(View.VISIBLE);
            l.startAnimation(anim);
        }
    };
    
    public static final int ACTIVITY_RECORD_SOUND = 0;
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    	super.onActivityResult(requestCode, resultCode, data);
    	
    	if(RESULT_OK == resultCode) {
    		if(ACTIVITY_RECORD_SOUND == requestCode) {
//                PhonebookSharingManager.addMsgSync(AbstractReaderActivity.this,
//                        "(no title)",//TODO: ask title here
//                        data.getDataString(),
//                        Message.MSG_TYPE_VOICE,
//                        friendID, dashboardID);
//
//				Toast.makeText(AbstractReaderActivity.this, "This message will be posted on next Sync!", Toast.LENGTH_SHORT).show();
//				finish();
    		    
    		    new SendVoiceMessageTask(this, dashboardID, null, data.getDataString()).execute("New Audio");
    		}
    	}
    }
    
    protected void preparePostText() {
        View postText = findViewById(R.id.post_text);
        if(postText instanceof ViewStub) {
            postText = ((ViewStub)postText).inflate();
        } else {
            postText = findViewById(R.id.post_text);
            postText.setVisibility(View.VISIBLE);
        }
        postText.startAnimation(anim);
        
        final EditText title = (EditText)postText.findViewById(android.R.id.text1),
                       text  = (EditText)postText.findViewById(android.R.id.text2);
        
        prefillTitle(title);
        
        postText.findViewById(android.R.id.button2).setOnClickListener(backListener);
        postText.findViewById(android.R.id.button1).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                TextMessageItem txtMsg = new TextMessageItem();
                txtMsg.title = title.toString();
                txtMsg.text  = text.toString();
                txtMsg.when  = GeneralUtils.getGmtTimeInMilis();
                
                new SendTextMessageTask(AbstractReaderActivity.this, 
                            String.format(Global.DASHBOARD_SERVLET_URL, "rm" /*ac*/, "" /*q*/, "" /*p*/, "" /*ps*/),
                            new DashboardReaderItem<ContactItem>(dashboardID, txtMsg)).execute();
            }
        });
    }
    
    protected void prefillTitle(EditText title) {
        //nothing
    }
    
    @Override
    protected void onDestroy() {
        super.onDestroy();

        anim = null;
    }
}
